package com.zzg.srb.sms.controller.api;

import com.zzg.srb.common.exception.Assert;
import com.zzg.srb.common.result.R;
import com.zzg.srb.common.result.ResponseEnum;
import com.zzg.srb.common.utils.RandomUtils;
import com.zzg.srb.common.utils.RegexValidateUtils;
import com.zzg.srb.sms.client.CoreUserInfoClient;
import com.zzg.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhengzg
 * @Date 2022/6/3 9:04
 * @Version 1.0
 */

@RestController
@RequestMapping("api/sms")
@Api("短信管理")
public class ApiSmsController {

    private Logger log = LoggerFactory.getLogger(ApiSmsController.class);

    @Resource
    private SmsService smsService;

    @Resource
    private CoreUserInfoClient coreUserInfoClient;

    @Resource
    private RedisTemplate redisTemplate;


    @ApiOperation("获取手机验证码")
    @ApiImplicitParam(name = "phone",value = "手机号",dataType = "String",required = true)
    @GetMapping("/send/{phone}")
    public R send(@PathVariable("phone") String phone){
        log.info("短信管理：ApiSmsController.send ======> " + phone);
        //校验手机号是否null
        Assert.notEmpty(phone, ResponseEnum.MOBILE_NULL_ERROR);

        //校验手机号是否合法
        Assert.isTrue(RegexValidateUtils.checkCellphone(phone),ResponseEnum.MOBILE_ERROR);

        //判断手机号是否已经被注册
        boolean isRegister = coreUserInfoClient.checkMobile(phone);
        Assert.isTrue(!isRegister,ResponseEnum.MOBILE_EXIST_ERROR);

        //生成随机验证码
        String code = RandomUtils.getFourBitRandom();

        //TODO 短信发送没有问题，先禁用
        //smsService.send(phone,code);

        //设置时间
        redisTemplate.opsForValue().set("srb:sms:code:" + phone,code, 5 , TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}
